﻿using AutoMapper;
using BW.MesProject.BasicData.Domain.Dto;
using BW.MesProject.BasicData.Domain.基础;
using BW.MesProject.BasicData.Infrastructure;
using BW.MesProject.Public.ErrorCode;
using BW.MesProject.Public.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace BW.MesProject.BasicData.Application
{
    /// <summary>
    /// 工作站管理服务实现类
    /// 提供工作站的增删改查等业务功能
    /// </summary>
    public class WorkstationManagServices : IWorkstationManagServices
    {
        private readonly IBaseRepository<WorkstationManagement> workstation;
        private readonly IMapper mapper;
        private readonly IBaseRepository<ProductionlineModel> productionline;

        /// <summary>
        /// 构造函数，通过依赖注入获取仓储和映射器
        /// </summary>
        /// <param name="workstation">工作站仓储接口</param>
        /// <param name="mapper">AutoMapper映射器</param>
        /// <param name="productionline">生产线仓储接口</param>
        public WorkstationManagServices(IBaseRepository<WorkstationManagement> workstation, IMapper mapper, IBaseRepository<ProductionlineModel> productionline)
        {
            this.workstation = workstation;
            this.mapper = mapper;
            this.productionline = productionline;
        }

        /// <summary>
        /// 添加工作站
        /// </summary>
        /// <param name="model">工作站模型</param>
        /// <returns>添加结果</returns>
        public ApiResult<int> AddWorkstation(WorkstationManagement model)
        {
            //mapp
            var models = mapper.Map<WorkstationManagement>(model);
            model.Id = YitIdHelper.NextId();
            model.IsDeleted = false;
            return new ApiResult<int>()
            {
                Code = ApiEnums.Success,
                Message = "添加成功",
                Data = workstation.Add(models),
            };
        }

        /// <summary>
        /// 删除工作站（逻辑删除）
        /// </summary>
        /// <param name="id">工作站ID</param>
        /// <returns>删除结果</returns>
        public ApiResult<int> DeleteWorkstation(long id)
        {
            //根据id来修改isdeleted为true
            var model = workstation.GetValue(x => x.Id == id);
            //查询是否有这个id没有就删除不了
            if (model == null)
            {
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = "删除失败",
                    Data = 0
                };
            }
            model.IsDeleted = true;
            return new ApiResult<int>()
            {
                Code = ApiEnums.Success,
                Message = "删除成功",
                Data = workstation.Update(model),
            };
        }

        /// <summary>
        /// 分页查询工作站，并关联生产线信息
        /// </summary>
        /// <param name="pageindex">页码</param>
        /// <param name="pagesize">每页大小</param>
        /// <param name="Workstationcode">工作站编码（可选）</param>
        /// <param name="Workstationname">工作站名称（可选）</param>
        /// <returns>分页结果</returns>
        public ApiPaging<List<WorkstationDto>> GetWorkstation(int pageindex, int pagesize, string? Workstationcode, string? Workstationname)
        {
            try
            {
                //查询工位数据
                var list = workstation.GetAll().Where(x => x.IsDeleted == false);
                if (!string.IsNullOrEmpty(Workstationcode))
                {
                    list = list.Where(x => x.Workstationcode.Contains(Workstationcode));
                }
                if (!string.IsNullOrEmpty(Workstationname))
                {
                    list = list.Where(x => x.Workstationname.Contains(Workstationname));
                }
                
                //获取产线数据
                var productionlineList = productionline.GetAll().Where(x => x.IsDeleted == false).ToList();
                
                //使用LINQ语句进行联查
                var result = from w in list.ToList()
                             join p in productionlineList 
                             on (long.TryParse(w.Productionid, out long productionIdLong) ? productionIdLong : 0) 
                             equals p.Id into pGroup
                             from p in pGroup.DefaultIfEmpty()
                             select new WorkstationDto
                             {
                                 Id = w.Id,
                                 Workstationname = w.Workstationname,
                                 Workstationcode = w.Workstationcode,
                                 Productionid = w.Productionid,
                                 Productionlinename = p != null ? p.Productionlinename : "",
                                 Processid = w.Processid,
                                 Workstationdescription = w.Workstationdescription,
                                 Workstationattributes = w.Workstationattributes,
                                 Workstationuserid = w.Workstationuserid,
                                 CreatedBy = w.CreatedBy,
                                 CreatedTime = w.CreatedTime,
                                 UpdatedBy = w.UpdatedBy,
                                 UpdatedTime = w.UpdatedTime,
                                 IsDeleted = w.IsDeleted
                             };
                
                var resultList = result.ToList();
                
                //分页
                return new ApiPaging<List<WorkstationDto>>()
                {
                    Code = ApiEnums.Success,
                    Message = "查询成功",
                    Data = resultList.Skip((pageindex - 1) * pagesize).Take(pagesize).ToList(),
                    TotalCount = resultList.Count
                };
            }
            catch (Exception ex)
            {
                return new ApiPaging<List<WorkstationDto>>()
                {
                    Code = ApiEnums.Fail,
                    Message = "查询失败：" + ex.Message,
                    Data = new List<WorkstationDto>(),
                    TotalCount = 0
                };
            }
        }

        /// <summary>
        /// 获取所有未删除的工作站
        /// </summary>
        /// <returns>工作站列表</returns>
        public ApiResult<List<WorkstationManagement>> GetWorkstationBy()
        {
           return new ApiResult<List<WorkstationManagement>>()
           {
               Code = ApiEnums.Success,
               Message = "查询成功",
               Data = workstation.GetAll().Where(x => x.IsDeleted == false).ToList(),
           };
        }

        /// <summary>
        /// 根据ID获取工作站
        /// </summary>
        /// <param name="id">工作站ID</param>
        /// <returns>工作站信息</returns>
        public ApiResult<WorkstationManagement> GetWorkstationById(long id)
        {
            return new ApiResult<WorkstationManagement>()
            {
                Code = ApiEnums.Success,
                Message = "查询成功",
                Data = workstation.GetValue(x => x.Id == id),
            };
        }

        /// <summary>
        /// 更新工作站信息
        /// </summary>
        /// <param name="model">工作站模型</param>
        /// <returns>更新结果</returns>
        public ApiResult<int> UpdateWorkstation(WorkstationManagement model)
        {
            //根据id来修改
            var model1 = workstation.GetValue(x => x.Id == model.Id);
            return new ApiResult<int>()
            {
                Code = ApiEnums.Success,
                Message = "修改成功",
                Data = workstation.Update(model),
            };
        }
    }
}
